package cn.itsource.controller;

import cn.itsource.util.AjaxResult;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/minio")
@Api(value = "文件上传的Api",description = "文件上传成功删除功能")
public class MinIoController {

    private static final String ACCESSKEY = "minioadmin";
    private static final String SECREKEY = "minioadmin123?";
    private static final String ADDRESS = "http://60.204.187.34:9090";
    private static final String BUCKETNAME = "java1210";

    //上传文件
    @ApiOperation("文件上传功能")
    @PostMapping
    public AjaxResult upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            String fileName = System.currentTimeMillis()+oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName)	//文件名
                .bucket(MinIoController.BUCKETNAME)  //存储目录名
                .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片

            //执行上传
            minioClient.putObject(putObjectArgs);
            return AjaxResult.me().setObj(fileName);

        } catch (Exception e) {
            return AjaxResult.me().setSuccess(false).setMessage("上传失败");
        }
    }

    @ApiOperation("删除文件功能")
    //删除文件
    @DeleteMapping("/{name}")
    public AjaxResult delete(@PathVariable("name")String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            minioClient.removeObject(MinIoController.BUCKETNAME, name);
            return new AjaxResult();
        } catch (Exception e) {
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    //批量删除minio中文章的封面
    @PatchMapping
    public AjaxResult patch(@RequestBody String[] articlePics){
        try {
            for (String pic : articlePics) {
                String picName = pic.substring(pic.lastIndexOf("/") + 1);
                delete(picName);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"批量删除minio的封面失败");
        }
    }

}